package com.nanhang.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nanhang.entity.TbSpecification;
import com.nanhang.entity.TbSpecificationExample;
import com.nanhang.mapper.TbSpecificationMapper;
import com.nanhang.service.SpecificationService;
import com.nanhang.util.PageResult;
import com.nanhang.vo.SpecificationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpecificationServiceImpl implements SpecificationService {
    @Autowired
    private TbSpecificationMapper tbSpecificationMapper;

    @Override
    public List<TbSpecification> findAll() {
        List<TbSpecification> tbSpecifications = tbSpecificationMapper.selectByExample(null);
        return tbSpecifications;
    }

    @Override
    public PageResult<TbSpecification> findByPage(Integer page, Integer pageSize) {
        //1. 开始分页
        PageHelper.startPage(page,pageSize);
        // 2. 开始查询数据
        List<TbSpecification> tbSpecifications = this.findAll();
        // 3. 将查询得到的数据转换为Page<Student>对象
        Page<TbSpecification> tbSpecificationPage = (Page<TbSpecification>) tbSpecifications;
        // 4. 转换为PageResult对象
        return new PageResult<>(tbSpecificationPage.getResult(), tbSpecificationPage.getTotal());
    }

    @Override
    public PageResult<TbSpecification> search(Integer page, Integer pageSize, SpecificationVO specificationVO) {
        // 1. 开始分页
        PageHelper.startPage(page, pageSize);
        // 2. 查询数据
        // 2.1 定义一次查询的实例
        TbSpecificationExample example = new TbSpecificationExample();
        // 2.2 添加查询条件到查询实例中
        TbSpecificationExample.Criteria criteria = example.createCriteria();
        if(StrUtil.isNotBlank(specificationVO.getSpecName())){
            criteria.andSpecNameLike("%" + specificationVO.getSpecName() + "%");
        }
        if(specificationVO.getId() != null && specificationVO.getId() != 0){
            criteria.andIdEqualTo(specificationVO.getId());
        }
        List<TbSpecification> tbSpecifications = tbSpecificationMapper.selectByExample(example);

        // 2.4 将上面的students对象转换为List集合
        Page<TbSpecification> studentPage = (Page<TbSpecification>) tbSpecifications;
        return new PageResult<>(studentPage.getResult(),studentPage.getTotal());
    }

    @Override
    public boolean save(TbSpecification tbSpecification) {
        return tbSpecificationMapper.insert(tbSpecification) > 0;
    }
}
